﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using log4net;
using System.Data;
using System.IO;
using System.Xml;

namespace Hutech.Authentication.Library.Helper
{
    public class TempXMLHelper
    {
        //cai nay sau se xay dung
        //private static readonly ILog log = LogManager.GetLogger(typeof(TempHelper));

        /// <summary>
        /// Save dataset into xml file
        /// </summary>
        /// <param name="xmlDataFile"></param>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static bool SaveTemporayDataAsXml(string xmlDataFile, DataSet ds)
        {
            if (!File.Exists(xmlDataFile))
            {
                XmlTextWriter writer = new XmlTextWriter(xmlDataFile, System.Text.Encoding.UTF8);
                writer.WriteStartDocument(true);
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 2;
                writer.Close();
            }
            try
            {
                ds.WriteXml(xmlDataFile, XmlWriteMode.WriteSchema);
                return true;
            }
            catch (UnauthorizedAccessException ex)
            {
                //log.Error("Lỗi không tạo được thư mục trong TKBHelper.VerifyTemporayFilesFolders", ex);
            }
            catch (System.Security.SecurityException ex)
            {
                //log.Error("Lỗi không có quyền ghi tập tin xml trong TKBHelper.VerifyTemporayFilesFolders", ex);
            }
            return false;
        }

        /// <summary>
        /// Read xml file and return dataset
        /// </summary>
        /// <param name="xmlDataFile"></param>
        /// <returns></returns>
        public static DataSet ReadTemporayDataFromXml(string xmlDataFile)
        {
            DataSet ds = new DataSet();
            try
            {
                foreach (DataTable dataTable in ds.Tables)
                    dataTable.BeginLoadData();

                ds.ReadXml(xmlDataFile, XmlReadMode.ReadSchema);

                foreach (DataTable dataTable in ds.Tables)
                    dataTable.EndLoadData();
            }
            catch { }
            return ds;
        }
    }
}